const app = getApp();

var util = require('../../utils/common.js'); //引入公共JS

import { Index } from 'index.model.js';
var index = new Index();

var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');

var qqmapsdk;
let leftHeight = 0,rightHeight = 0; //分别定义左右两边的高度

let query;
var num = 1;
var __city = '';
var searchRequest;
Page({
  data: {
    list: [],
    leftList: [],
    rightList: [],
    currentTab: 0,
    //资讯切换
    currentList: 0,
    cityData: "全国",
    ScrollHeight: '100',
    //demo高度
    searchFlag: true,
    //搜索
    cityFlag: true,
    //城市
    SearchClose: true,
    SearchTo: false,
    remind: true,
    //复工通知
    source: '',
    //来源判断
    iconArray: [{
      "cateId": '4',
      "cateList": '4',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/classify_1.png',
      "iconText": '景区门票'
    }, {
      "cateId": '41',
      "cateList": '11',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/classify_2.png',
      "iconText": '民宿客栈'
    }, {
      "cateId": '19',
      "cateList": '3',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/classify_3.png',
      "iconText": '演出门票'
    }, {
      "cateId": '10',
      "cateList": '7',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/classify_4.png',
      "iconText": '吃喝玩乐'
    }, {
      "cateId": '2',
      "cateList": '1',
      "iconUrl": 'https://img.dahepiao.com/wap/images/icon_qingming.png',
      "iconText": '清明踏青'
    }, {
      "cateId": '20',
      "cateList": '9',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/icos_6.png',
      "iconText": '音乐会'
    }, {
      "cateId": '22',
      "cateList": '6',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/icos_7.png',
      "iconText": '亲子剧'
    }, {
      "cateId": '6',
      "cateList": '2',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/icos_8.png',
      "iconText": '温泉'
    }, {
      "cateId": '11',
      "cateList": '3',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/icos_9.png',
      "iconText": '夏季玩水'
    }, {
      "cateId": '25',
      "cateList": '5',
      "iconUrl": 'https://www.hanzhuo123.com/app_img/icos_11.png',
      "iconText": '特价秒杀'
    }],
    kefuphoneArr: []
  },

  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    tt.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude;
        var longitude = res.longitude;
        tt.setStorageSync('latitude', latitude); //纬度
        tt.setStorageSync('longitude', longitude); //经度
        console.log('经纬度',res)
        vm.getLocal(latitude, longitude);
      },
      fail: function (res) {
        var dizhi = '';
        tt.setStorageSync('latitude', ''); //纬度
        tt.setStorageSync('longitude', ''); //经度
        if (__city) {
          dizhi = __city;
        }
        var latitude = '';
        var longitude = '';
        index.getSpecialPrice(dizhi, latitude, longitude, res => {
          //特价抢购
          vm.setData({
            'getSpecialPrice': res,
            'discount': (res[0]['yhprices'] / res[0]['mprices'] * 10).toFixed(1),
            'discount1': (res[1]['yhprices'] / res[1]['mprices'] * 10).toFixed(1)
          });
        });
      }
    });
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log('地理位置',res)
        let province = res.result.ad_info.province;
        let city = res.result.ad_info.city; //设置缓存（吧用户地址信息存入缓存）

        tt.setStorageSync('wxcity', city);
        tt.setStorageSync('_city', city);
        tt.setStorage({
          key: 'wxprovince',
          data: province
        });
        vm.setData({
          province: province,
          city: city,
          cityData: city,
          latitude: latitude,
          longitude: longitude
        }); //显示2秒隐藏加载提示

        setTimeout(function () {
          vm._cityget();
        }, 1000);
      },
      fail: function (res) {
        console.log("error");
      }
    });
  },

  //上拉加載判斷高度
  async isLeft() {
    const {list,leftList,rightList} = this.data;
    // query = tt.createSelectorQuery();
    for (const item of list) {
      leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度，来觉得添加到那边
      await this.getBoxHeight(leftList, rightList);
    }
  },
  //輸出上拉
  getBoxHeight(leftList, rightList) {
    //获取左右两边高度
    return new Promise((resolve, reject) => {
      this.setData({
        leftList,
        rightList
      }, () => {
        query = tt.createSelectorQuery();
        query.select('#left').boundingClientRect();
        query.select('#right').boundingClientRect();
        query.exec(res => {
          if(res){
             leftHeight = res[0].height; //获取左边列表的高度
              rightHeight = res[1].height; //获取右边列表的高度
              resolve();
          }
        });
      });
    });
  },

  onLoad: function (e) {
    console.log('手页',e)
    if(e._city){
      __city = e._city
    }
    
    index.getShuffling('郑州市', res => {
      this.setData({
        movies: res
      });
    });

    var source = e.source;
    this.setData({
      num:num
    })
    if(source){
      wx.setStorageSync('source', source);
    }

    qqmapsdk = new QQMapWX({
      key: '5XNBZ-SFPRU-M35VS-BNF67-DIHHJ-AEFD7' //这里自己的key秘钥进行填充
    });
    var that = this;
    tt.getStorage({
      key: 'wxcity',
      success: function (res) {
        console.log(res)
        if (__city) {
          res.data = __city;
        } else if (res.data == '') {
          res.data = '全国';
        }
        that.setData({
          'cityData': res.data
        });
      }
    });

    if(e._city){
      this._cityget()
    }else{
      this.getLocation();
    }

    tt.removeStorageSync("t_ypeid"); //清空缓存
    tt.removeStorageSync("styleid1"); //清空缓存
    tt.removeStorageSync("styleid2"); //清空缓存
    tt.removeStorageSync("styleid3"); //清空缓存
    tt.removeStorageSync("styleid4"); //清空缓存
    tt.removeStorageSync("c_ity"); //清空缓存

    // 获取客服手机号
    let kefuphone = tt.getStorageSync('kefuphoneArr');
    if (!kefuphone) {
      util.kefuphone();
    }
    this.setData({
      kefuphoneArr: kefuphone.slice(0, 2)
    });
  },

  //关闭页面时隐藏城市弹框
  onHide: function () {
    this.setData({
      cityFlag: true,
      //关闭城市
      searchFlag: true,
      //关闭搜索列表
      SearchVal: "",
      //清空输入框的值
      SearchClose: true,
      SearchTo: false
    });
  },
  _cityget: function () {
    var that = this;
    var latitude = tt.getStorageSync('latitude');
    var longitude = tt.getStorageSync('longitude');
    var wxcity = tt.getStorageSync('_city');
    console.log('轮播',wxcity)
      //轮播图 
     index.getBannerData(wxcity, res => {
      that.setData({
        'bannerArr': res
      });
    });

    tt.getStorage({
      key: 'wxcity',
      success: function (res) {
        var dizhi = res['data'];
        if (__city) {
          dizhi = __city;
        }
        index.getSpecialPrice(dizhi, latitude, longitude, res => {
          console.log('特价',res)
          //特价抢购
          that.setData({
            'getSpecialPrice': res,
            'discount': (res[0]['yhprices'] / res[0]['mprices'] * 10).toFixed(1),
            'discount1': (res[1]['yhprices'] / res[1]['mprices'] * 10).toFixed(1)
          });
        });
        var type = '精选';
        var city = dizhi;
        var head = 0;
        var tail = 6;
        tt.setStorageSync('type', type);
        tt.setStorageSync('head', head);

        if (__city) {
          city = __city;
        }

        index.getHomeList(type, city, head, tail, latitude, longitude, res => {
          //热门推荐
          that.data.list = res;
          that.isLeft();
          that.setData({
            'getHomeList': res
          });
        });

      },
      fail: function (res) {
        var dizhi = '';
        var latitude = '';
        var longitude = '';
        if (__city) {
          dizhi = __city;
        }
        index.getSpecialPrice(dizhi, latitude, longitude, res => {
          //特价抢购 
          that.setData({
            'getSpecialPrice': res,
            'discount': (res[0]['yhprices'] / res[0]['mprices'] * 10).toFixed(1),
            'discount1': (res[1]['yhprices'] / res[1]['mprices'] * 10).toFixed(1)
          });
        });
      }
    });
  },

  //消失添加到我的小程序提醒
  disappear: function () {
    var remind = true;
    this.setData({
      remind: remind
    });
  },
  //打开选择城市
  onChangeCity: function (e) {
    this.setData({
      cityFlag: false,
      searchFlag: true,
      //关闭搜索列表
      SearchVal: "",
      //清空输入框的值
      SearchClose: true,
      SearchTo: false
    });
  },
  //点击分类跳转到列表页
  cateClick: function (e) {
    var _cateId = e.currentTarget.dataset.cate; //获取到cateId
    var _cateList = e.currentTarget.dataset.list; //首页传到列表页，列表页获取到值滚动距离
    var _city = '';
    console.log(e.currentTarget.dataset);
    tt.setStorageSync('_city', _city);
    tt.setStorageSync('_cateId', _cateId);
    tt.setStorageSync('_cateList', _cateList);
    console.log(tt.getStorageSync('_cateId'), tt.getStorageSync('_cateList', _cateList));

    if (_cateList == 9 || _cateId == 19 || _cateList == 6) {
      tt.switchTab({
        url: '../yclist/yclist',
        //点击跳转到列表页
        success: function () {
          var page = getCurrentPages().pop();
          console.log(page);
          if (page == undefined || page == null) return;
          page.onLoad(e);
        }
      });
    } else if (_cateList == 1) {
      tt.navigateTo({
        // pages/activity/activity
        url: '../activity/activity' //跳转链接

      });
    } else if (_cateList == 4) {
      tt.navigateTo({
        // pages/activity/activity
        url: '../jqIndex/jqIndex' //跳转链接

      });
    } else {
      tt.switchTab({
        url: '../jqList/jqList',
        //点击跳转到列表页
        success: function () {
          var page = getCurrentPages().pop();
          console.log(page);
          if (page == undefined || page == null) return;
          page.onLoad(e);
        }
      });
    }
  },
  scrollClick: function (e) {
    var _city = '';
    var _cateId = e.currentTarget.dataset.cate; //获取到cateId

    var _cateList = e.currentTarget.dataset.list; //首页传到列表页，列表页获取到值滚动距离

    tt.setStorageSync('_city', _city);
    tt.setStorageSync('_cateId', _cateId);
    tt.setStorageSync('_cateList', _cateList);
    tt.switchTab({
      url: '../yclist/yclist',
      //点击跳转到列表页
      success: function () {
        var page = getCurrentPages().pop();
        if (page == undefined || page == null) return;
        page.onLoad(e);
      }
    });
  },
  //打开搜索
  searchValue: function (e) {
    var _data = e.detail.value;
    this.data.SearchValue = e.detail.value;
    var patt3 = /^[\u4e00-\u9fa5]{2,20}$/; //正则验证汉字不能少两个，不能多余20个

    this.setData({
      //保存输入框的值
      SearchVal: e.detail.value
    });
    this.data.datarow = _data;
    var that = this;
    clearTimeout(searchRequest);
    searchRequest = setTimeout(() => {
      if (_data == '') {
        that.setData({
          searchFlag: true,
          SearchClose: true,
          SearchTo: false,
          SearchVal: "" //清空输入框的值

        }); // } else if(patt3.test(_data)){
      } else if (patt3.test(_data)) {
        //搜索页面
        index.getSearchFor(that.data.datarow, res => {
          if (!res) {
            that.setData({
              'SearchFor': 20000
            });
          } else {
            var a = [];
            var b = [];

            for (var i in res) {
              if (res[i]['ycjq'] == '演出') {
                a.push(res[i]['shorttitle']);
              } else {
                b.push(res[i]['shorttitle']);
              }
            }

            if (a != '' && b != '') {
              var aa = 1;
            } else {
              var aa = 2;
            }

            that.setData({
              'SearchFor': res,
              searchFlag: false,
              SearchClose: false,
              SearchTo: true,
              aa: aa,
              datarow: that.data.datarow
            });
          }
        });
      }
    }, 1000);
  },
  //关闭搜索
  onCloseSearch: function () {
    this.setData({
      searchFlag: true,
      SearchClose: true,
      SearchTo: false,
      SearchVal: "" //清空输入框的值

    });
  },
  //使用回车键搜索
  searchEnter: function () {
    this.setData({
      searchFlag: true,
      SearchClose: true,
      SearchTo: false,
      SearchVal: "" //清空输入框的值

    });
    var inputdata = this.data.SearchValue;

    if (inputdata) {
      tt.navigateTo({
        url: '../ycSearch/ycSearch?inputdata=' + inputdata
      });
    }
  },
  //点击关闭按钮关闭搜索框
  toClose: function () {
    this.setData({
      searchFlag: true,
      //关闭搜索列表
      SearchClose: true,
      //打开关闭搜索图标
      SearchTo: false,
      //关闭搜索图标
      SearchVal: "" //清空输入框的值

    });
  },
  //分享
  onShareAppMessage: function () {
    util.sharePage();
  },
  // 拨打电话
  calling: function () {
    util.calling();
  },
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    if (e.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },

  //上拉加载
  onReachBottom(e) {
    var city = tt.getStorageSync('wxcity');
    var type = tt.getStorageSync('type');
    var head = tt.getStorageSync('head') + 6;
    var latitude = tt.getStorageSync('latitude');
    var longitude = tt.getStorageSync('longitude');
    var tail = 6;

    if (__city) {
      city = __city;
    }

    index.getHomeList(type, city, head, tail, latitude, longitude, res => {
      //热门推荐
      this.data.list = res;
      this.isLeft();
      this.setData({
        'getHomeList': res
      });
      tt.setStorageSync('wxcity', city);
      tt.setStorageSync('type', type);
      tt.setStorageSync('head', head);
    });
  },

  //点击跳转景区列表民宿
  hotel: function () {
    var _cateId = 41; //获取到cateId

    var _cateList = 11; //首页传到列表页，列表页获取到值滚动距离

    var _city = '';
    tt.setStorageSync('_city', _city);
    tt.setStorageSync('_cateId', _cateId);
    tt.setStorageSync('_cateList', _cateList);
    tt.switchTab({
      url: '../jqList/jqList',
      //点击跳转到列表页
      success: function () {
        var page = getCurrentPages().pop();
        if (page == undefined || page == null) return;
        page.onLoad(e);
      }
    });
  },
  //点击跳转景区列表9.9特价
  SpecialOffer: function () {
    var _cateId = 12; //获取到cateId

    var _cateList = 12; //首页传到列表页，列表页获取到值滚动距离

    var _city = '';
    tt.setStorageSync('_city', _city);
    tt.setStorageSync('_cateId', _cateId);
    tt.setStorageSync('_cateList', _cateList);
    tt.switchTab({
      url: '../jqList/jqList',
      //点击跳转到列表页
      success: function () {
        var page = getCurrentPages().pop();
        if (page == undefined || page == null) return;
        page.onLoad(e);
      }
    });
  },
  //景区项目详情，特价抢购
  ScenicSpotDetails: function (e) {
    var id = e.currentTarget.dataset.id;
    tt.navigateTo({
      url: '../jqdetail/jqdetail?id=' + id //跳转链接

    });
  },
  //热门推荐类型转换
  listClick: function (e) {
    var Category = e.currentTarget.dataset.list; //类型

    var num = e.currentTarget.dataset.num;
    tt.setStorageSync('type', Category);
    tt.setStorageSync('head', 0);
    var that = this;
    that.setData({
      num: num,
      leftList: [],
      rightList: []
    });
    var city = tt.getStorageSync('wxcity');
    var type = tt.getStorageSync('type');
    var head = tt.getStorageSync('head');
    var latitude = tt.getStorageSync('latitude');
    var longitude = tt.getStorageSync('longitude');
    var tail = 6;

    if (__city) {
      city = __city;
    }

    index.getHomeList(type, city, head, tail, latitude, longitude, res => {
      //热门推荐
      that.data.list = res;
      that.isLeft();
      that.setData({
        'getHomeList': res
      });
      tt.setStorageSync('wxcity', city);
      tt.setStorageSync('type', type);
      tt.setStorageSync('head', head);
    });
  },
  //热门推荐点击进入景区详情
  DetailsClick: function (e) {
    var aid = e.currentTarget.dataset.aid;
    var jqyc = e.currentTarget.dataset.jqyc;

    if (jqyc == '景区') {
      tt.navigateTo({
        url: '../jqdetail/jqdetail?id=' + aid
      });
    } else {
      var id = e.currentTarget.dataset.id;
      tt.navigateTo({
        url: '../ycdetail/ycdetail?id=' + id
      });
    }
  },
  //页面滑动到底部
  bindDownLoad: function () {
    var that = this;
    loadMore(that);
  },
  //回到顶部
  goTop: function () {
    util.goTop();
  },
  //关闭公告
  gg_Close: function () {
    this.setData({
      gonggao: true
    });
  }
});